package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.article.entity.ApAuthor;
import com.heima.article.feign.ArticleFeign;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.enums.UserEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.user.dto.FollowBehaviorDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserFollowService;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-03-23
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private IApUserFollowService userFollowService;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 用户关注行为话题
     */
    @Value("${topic.followBehaviorTopic}")
    private String followBehaviorTopic;


    @Override
    public ResponseResult login(LoginDto dto) {
        //1.校验用户提交参数是否为空
        if (dto == null || (StringUtils.isBlank(dto.getPhone()) && StringUtils.isBlank(dto.getPassword()) && StringUtils.isBlank(dto.getEquipmentId()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.根据账户名称查询用户信息（得到用户盐salt信息 跟 正确密文）
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())) {
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUser::getPhone, dto.getPhone());
            ApUser one = this.getOne(queryWrapper);
            if (one == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }


            //3.校验用户填写密码是否正确
            //3.1 拿着用户填写明文密码+盐 进行Md5加密 得到密文
            String pwdStr = dto.getPassword() + one.getSalt();
            String userEnterPwdEncoderStr = DigestUtils.md5DigestAsHex(pwdStr.getBytes());

            //3.2 判断上面步骤得到的密文 跟 数据库中正确密文是否一致
            if (!one.getPassword().equals(userEnterPwdEncoderStr)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }


            //4.调用JWT工具类生成令牌
            Map<String, Object> claimMaps = new HashMap<>();
            claimMaps.put("userId", one.getId());
            claimMaps.put("userName", one.getName());
            String token = AppJwtUtil.getToken(claimMaps);

            //5.封装响应结果业务数据
            //5.1 数据脱敏
            one.setPassword(null);
            one.setSalt(null);
            one.setPhone(null);

            //5.2 通过Map构建要求响应结果
            HashMap<String, Object> mapResult = new HashMap<>();
            mapResult.put("user", one);
            mapResult.put("token", token);
            return ResponseResult.okResult(mapResult);
        }

        //5. 用户点击了“先看看”使用手机设备进行登录
        if (StringUtils.isNotBlank(dto.getEquipmentId())) {
            Map<String, Object> claimMaps = new HashMap<>();
            claimMaps.put("userId", 0);
            claimMaps.put("equipmentId", dto.getEquipmentId());
            String token = AppJwtUtil.getToken(claimMaps);

            HashMap<String, Object> mapResult = new HashMap<>();
            mapResult.put("token", token);
            return ResponseResult.okResult(mapResult);
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
    }


    /**
     * 关注|取消关注 作者
     *
     * @param dto 关注信息
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //1.构建关注记录对象,属性赋值
        ApUserFollow apUserFollow = new ApUserFollow();
        //1.1 获取当前登录用户（粉丝信息）
        User user = UserThreadLocalUtil.get();
        apUserFollow.setUserId(user.getUserId());
        apUserFollow.setUserName(user.getUserName());

        //1.2 获取关注用户的APP用户ID（博主信息）
        //1.2.1 远程调用文章微服务：根据作者ID查询作者信息
        ResponseResult<ApAuthor> responseResult = articleFeign.getAuthorById(dto.getAuthorId());
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApAuthor author = responseResult.getData();
            apUserFollow.setFollowId(author.getUserId());
            apUserFollow.setFollowName(author.getName());

            //1.3 设置喜欢级别
            apUserFollow.setLevel(UserEnum.USER_FOLLOW_LEVEL_ONCE.getVal());


            //2.执行新增关注记录 或者 删除
            Integer operation = dto.getOperation();

            LambdaQueryWrapper<ApUserFollow> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUserFollow::getUserId, user.getUserId());
            queryWrapper.eq(ApUserFollow::getFollowId, author.getUserId());

            //2.1 判断用户操作行为：关注 还是 取消关注
            if (operation.equals(UserEnum.USER_FOLLOW_OPRATION.getVal())) {
                //2.2 关注第一次关注直接保存
                ApUserFollow follow = userFollowService.getOne(queryWrapper);
                if (follow == null) {
                    userFollowService.save(apUserFollow);
                }
            } else {
                //2.3 取消关注 删除关注记录
                userFollowService.remove(queryWrapper);
            }

            //3.TODO 发送消息到Kafka，异步记录用户行为
            //3.1 构建关注行为DTO对象
            FollowBehaviorDto behaviorDto = new FollowBehaviorDto();
            behaviorDto.setUserId(user.getUserId());
            behaviorDto.setFollowId(author.getUserId());
            behaviorDto.setOperation(dto.getOperation());
            behaviorDto.setEquipmentId(dto.getEquipmentId());
            //3.2 发送关注行为消息到Kafka
            kafkaTemplate.send(followBehaviorTopic, JSON.toJSONString(behaviorDto));
        }
        return ResponseResult.okResult();
    }
}
